unit WebAPI.Invoker;

interface

uses
  WebAPI.Intf, JSON;

type
  /// <summary>
  /// This class is a layer between the webserver, which receives requests and an API, which handles these requests.
  /// </summary>
  TWebAPIInvoker = class
  public
    /// <summary>
    /// Invokes the method named <paramref name="aCommand" /> on object <paramref name="aAPI"/> and passes <paramref name="aParam"/> as Parameter
    /// </summary>
    class function Invoke(const aAPI: IWebAPI; const aCommand: string; aParam: IJSONObject): string;
  end;

implementation

uses
  Rtti, SysUtils;

{ TWebAPIInvoker }

class function TWebAPIInvoker.Invoke(const aAPI: IWebAPI; const aCommand: string; aParam: IJSONObject): string;
var
  o: TObject;
  ctx: TRttiContext;
  typ: TRttiType;
  m: TRttiMethod;
begin
  o := TObject(aAPI);
  typ := ctx.GetType(o.ClassInfo);
  m := typ.GetMethod(aCommand);
  if assigned(m) then
  begin
    result := m.Invoke(o, [TValue.From<IJSONObject>(aParam)]).AsString;
  end
  else
    raise Exception.Create('Unknown Command: "' + aCommand + '"');
end;

end.
